// pages/gouwc/gouwc.js
const app = getApp()
import request from '../../utils/http.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startX: 0, // 开始X坐标
    startY: 0, // 开始Y坐标
    iscount:0,
    personId:0,
    IsLogin:false,
    dianPuId:0,
    gwcList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

    //获取购物车产品
    getGWCList: function () {

      var that = this

        // wx.showLoading({
        //   title: '获取中...',
        //   mask: true
        // })
        let data = {
          dianPuId: that.data.dianPuId,
          personId: that.data.personId,
        }
        request.get('gouWuChe/xiangQing', data, res => {
         console.log("购物车:" + JSON.stringify(res.data))
          res.data.list.forEach((item, index) => {        
            item.isTouchMove = false;     
          })
      

          that.setData({
            gwcList: res.data.list,
            iscount: res.data.list.length,
          })
          that.countPrice();
          // wx.hideLoading();
        })

    },



    
  //选中购物车产品
  selectOneCheck: function (e) {
    var index = e.currentTarget.dataset.index;
    var flag = !this.data.gwcList[index].checked ? 2 : 1
    this.setData({
      ['gwcList[' + index + '].checked']: !this.data.gwcList[index].checked,
    })
   // console.log("flag:" + flag)
    this.selectOneCheckAction(flag, this.data.gwcList[index].productId)

    // this.countPrice();
  },

  //修改选中产品
  selectOneCheckAction: function (flag, zhongXinProductId) {

    var that = this
    let data = {
      flag: flag,
      zhongXinProductId: zhongXinProductId,
      dianPuId:that.data.dianPuId,
      personId: that.data.personId,
    }
    request.get('gouWuChe/check', data, res => {

      // console.log("respon:"+JSON.stringify(res.data))


      if (res.data.status == 1) {
        that.getGWCList();
      } else {
        var mesage = res.data.message
        wx.showToast({
          title: mesage, // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      }




    })
  },




  //是否全选
  idCheckAll: function (flag, dianPuId) {

    this.setData({
      allCheck: !this.data.allCheck
    })

    var that = this

    let data = {
      flag: that.data.allCheck ? 2 : 1,
      dianPuId: that.data.dianPuId,
      personId: that.data.personId,
    }
    request.get('gouWuChe/allStatus', data, res => {

      // console.log("respon:"+JSON.stringify(res.data))


      if (res.data.status == 1) {
        that.getGWCList();
      } else {
        var mesage = res.data.message
        wx.showToast({
          title: mesage, // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      }




    })


  },

  //计算购物车数量和价格
  countPrice: function () {
    var that = this

    that.setData({
      allCount: 0,
      countPrice: 0
    })
    var tempAllCheck = true

    for (var i = 0; i < that.data.gwcList.length; i++) {
      if (that.data.gwcList[i].checked && that.data.gwcList[i].productKuCun>0) {
        that.setData({
          allCount: parseInt(that.data.allCount) + parseInt(that.data.gwcList[i].shuLiang),
          countPrice: (parseInt(that.data.countPrice * 100) + parseInt(that.data.gwcList[i].shiJiJiaGe * that.data.gwcList[i].shuLiang * 100)) / 100
        })
      } else {
        tempAllCheck = false;
      }

    }
    this.setData({
      allCheck: tempAllCheck
    })


  },

  //数量减少
  bindReduceTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var oneZengSongShu = e.currentTarget.dataset.id;
    if (this.data.gwcList[index].shuLiang  > this.data.gwcList[index].qiGouShuLiang) {
      this.setData({
        ['gwcList[' + index + '].shuLiang']: parseInt(this.data.gwcList[index].shuLiang) - 1,
        ['gwcList[' + index + '].checked']: true,
      })

      if (this.data.gwcList[index].zengPinModel.shuLiang  > 0) { 
        this.setData({     
          ['gwcList[' + index + '].zengPinModel.shuLiang']: parseInt(this.data.gwcList[index].zengPinModel.shuLiang) - oneZengSongShu,
        })
      }
      this.gwcAction(this.data.gwcList[index].productId,this.data.gwcList[index].zengPinModel.zengSongChanPinId,2);

    } else {

      var that = this
      wx.showModal({
        title: '',
        content: '您真的要删除这个商品吗？',
        showCancel: true, //是否显示取消按钮
        cancelText: "删除", //默认是“取消”
        cancelColor: '#696868', //取消文字的颜色
        confirmText: "再想想", //默认是“确定”
        confirmColor: '#f07d12', //确定文字的颜色
        success: function (res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            that.delOnePro(e);

          } else {
            //点击确定，不删除

          }
        },
        fail: function (res) {}, //接口调用失败的回调函数
        complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
      })

    }

    this.countPrice();

  },

  //数量增加
  bindAddTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var oneZengSongShu = e.currentTarget.dataset.id;
    // console.log(parseInt(this.data.countPrice*100));
    // console.log(parseInt(this.data.gwcList[index].price*100))

    if(parseInt(this.data.gwcList[index].productKuCun)>parseInt(this.data.gwcList[index].shuLiang)){
      this.setData({
        ['gwcList[' + index + '].shuLiang']:(parseInt(this.data.gwcList[index].shuLiang) + 1),
        ['gwcList[' + index + '].checked']: true,
      })

      if (parseInt(this.data.gwcList[index].zengPinModel.shuLiang)> 0) { 
        this.setData({
          ['gwcList[' + index + '].zengPinModel.shuLiang']:(parseInt(this.data.gwcList[index].zengPinModel.shuLiang) + oneZengSongShu),
        })
      }


    }

 


    this.countPrice();
    this.gwcAction(this.data.gwcList[index].productId,this.data.gwcList[index].zengPinModel.zengSongChanPinId,1);
  },

  //删除购物车产品
  delOnePro: function (e) {

    var index = e.currentTarget.dataset.index;

    var that = this
    let data = {
      zhongXinProductId: that.data.gwcList[index].productId,
      personId: that.data.personId,
      dianPuId:that.data.dianPuId
    }
    request.get('gouWuChe/delete', data, res => {

      // console.log("respon:"+JSON.stringify(res.data))
      if (res.data.status == 1) {
        that.data.gwcList.splice(index, 1)
        that.setData({
          gwcList: that.data.gwcList
        })
        if (that.data.gwcList.length == 0) {
          that.setData({
            iscount: 0
          })
        }
      }

      that.countPrice();
    })


  },


  //跳转到商城页面
  toShopping: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  //产品详情页
  toProductInfo: function (e) {
    var productId = e.currentTarget.dataset.id;
    //console.log("productId:" + productId)
    wx.navigateTo({
      url: '/pages/productInfo/productInfo?productId=' + productId,
    })
  },

  //执行增减操作
  gwcAction: function (productId,zengSongChanPinId, flag) {
    var that = this
    let data = {
      zhongXinProductId: productId,
      personId: that.data.personId,
      dianPuId:that.data.dianPuId,
      zengSongChanPinId:zengSongChanPinId,
      flag: flag, //增加
    }
    request.get('gouWuChe/addReduce', data, res => {

      // console.log("flag:" + flag + '=====' + JSON.stringify(res.data))


    })
  },

  //订单结算页面
  toOrdersInfo: function () {
    if (this.data.allCount > 0) {
      wx.navigateTo({
        url: '/pages/orders_queren/orders_queren?type=1',
      })
    } else {
      wx.showToast({
        title: '您还未选产品！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }

  },

      // 手指触摸开始事件，记录开始的(X,Y)位置
  touchStart: function (e) {
    // 开始触摸时,将 isTouchMove 为 true 的置为 false，开始新的操作
    this.data.gwcList.forEach(function (item, index) {

        if (item.isTouchMove)
        item.isTouchMove = false;

      
    })

    // 更新数据，记录开始的位置
    // console.log('startX:'+e.changedTouches[0].clientX)
    // console.log('startY:'+e.changedTouches[0].startY)
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      gwcList: this.data.gwcList
    })
  },

  // 手指滑动事件
  touchMove: function (e) {
    // 定义变量进行数据存储
    let that = this
    let currentIndex = e.currentTarget.dataset.index //当前索引
    let startX = that.data.startX // 开始X坐标
    let startY = that.data.startY // 开始Y坐标
    let touchMoveX = e.changedTouches[0].clientX // 滑动变化X坐标
    let touchMoveY = e.changedTouches[0].clientY // 滑动变化Y坐标

    that.data.gwcList.forEach((item, index) => {
      item.isTouchMove = false
     // 判断当前点击的是哪一个，进行操作
      if (index == currentIndex) {
        if (touchMoveX > startX) // 滑动位置大于开始位置 => 右滑
          item.isTouchMove = false
        else // => 左滑
          item.isTouchMove = true
      }
  

    })

    //更新数据
    that.setData({
      gwcList: that.data.gwcList
    })
  },

  // 删除事件
  del: function (e) {
    var id=e.currentTarget.dataset.index
    var that=this
    let data = {
      zhongXinProductId: id,
      dianPuId:that.data.dianPuId
    }
  
    request.get('dianPu/tingShouYiGeDianPuChanPin', data, res => {

      if(res.data.status==1){
        that.getzaiShouPro()
        app.globalData.shopIsChange='true'
      }else{
        wx.showToast({
          title: '下架失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      }
  
    }, err => {
      wx.showToast({
        title: '处理失败', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }

    
    this.setData({
      personId: wx.getStorageSync(app.globalData.PERSON_ID) == "" ? 0 : wx.getStorageSync(app.globalData.PERSON_ID),
      IsLogin: wx.getStorageSync(app.globalData.LOGINSTATUS),
      dianPuId:wx.getStorageSync(app.globalData.SHOPID),
    })
     this.getGWCList();


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})